<?php

/** Soooner_View_Template */
require_once ROOT_PATH . '/library/Soooner/View/Template.php';
/** Soooner_Controller_Acl */
//require_once ROOT_PATH . '/library/Soooner/Controller/Acl.php';

class Soooner_Controller_Action extends Zend_Controller_Action
{
    protected $_userId;
    protected $_userName;
    protected $_acl;
    protected $_auth;
    protected $_session;
    protected $_userinfo;
    protected $_processlist;
    protected $_configs;

    /**
     * 模板参数信息
     * @var array
     */
    protected $_dzTemplate = array();

    /**
     * 构造方法
     * @return void
     */
    public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
    {
        Zend_Session::start();
        $this->_auth = Zend_Auth::getInstance()
             ->setStorage(new Zend_Auth_Storage_Session('authNameSpace'));
        $this->_session = new Zend_Session_Namespace('authNameSpace');

        $non_need_login['index'] = array('cap','login','logout','ajax');
        if (!array_key_exists($request->getControllerName(), $non_need_login) ||
            !in_array($request->getActionName(), $non_need_login[$request->getControllerName()])
        )
        {
            if (!$this->_auth->hasIdentity())
            {
                exit('<script>window.location.href=\'/index/login/\'</script>');
            }
            $this->_userinfo = (array)$this->_auth->getStorage()->read();
            $this->_userinfo['roles'] = empty($this->_userinfo['roles']) ? '' : substr($this->_userinfo['roles'], 1, -1);
            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            $this->initRolePriv();
            $this->checkAllow($request->getControllerName(), $request->getActionName(), true);
            $this->_configs = $this->getConfig();
        }
        parent::__construct($request, $response, $invokeArgs);
    }

    public function preDispatch()
    {
    	$d = date('Y-m-d', time());
        $logger = new Zend_Log();
        $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . "/cache/log.".$this->_userinfo['username'].".".$this->_userinfo['userid'].".".$d.".txt");
//      $format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL;
        $format = new Zend_Log_Formatter_Xml('log', array(
                   'msg' => 'message', 
                   'level' => 'priorityName',
                   'ctr' => 'abc',
                   'act' => 'def'
               ));
//        $formatter = new Zend_Log_Formatter_Simple($format);
        $writer->setFormatter($format);
        $logger->addWriter($writer);
        if($this->getRequest()->isPost())
        {
            $params =$this->getRequest()->getPost();
            $params = implode(";",$params);
        }
        $t = date('Y-m-d H:i:s', time());
        $iipp=$_SERVER["REMOTE_ADDR"];        
        //$logger->info( $t.":".$iipp.":".$this->getRequest()->getControllerName().'/'.$this->getRequest()->getActionName().":".$params );
    }
    public function initDzTemplate()
    {
        $this->_dzTemplate = new Soooner_View_Template();
    }
    protected function initRolePriv()
    {
        $frontend = 'Core';
        $frontendOptions = array(
            'caching' => true,
            'lifetime' => 60,
            'automatic_serialization' => true
        );
        $backend = 'File';
        //$backend = 'APC';
        //$backendOptions = array();
        $backendOptions = array(
            'cache_dir' => APPLICATION_PATH . '/cache',
            'file_name_prefix' => 'zend_acl_cache'
        );
        //实例化缓存对象
        $coreCache = Zend_Cache::factory($frontend, $backend, $frontendOptions, $backendOptions);
        //初始化资源权限
        if (!$this->_acl['resource'] = $coreCache->load('resource'))
        {
            $exists_mvcctr = array();
            $exists_mvcaction = array();
            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            $this->_acl['resource'] = new Zend_Acl();
            $r_role_ids = $dbAdapter->fetchAll("SELECT roleid FROM role WHERE roleid!=1 ");
    //        $role_ids = array();
            if (is_array($r_role_ids) && !empty($r_role_ids))
            {
                foreach ($r_role_ids as $i)
                {
    //              $role_ids[] = $i['roleid'];
                    $this->_acl['resource']->addRole(new Zend_Acl_Role($i['roleid']));
                }
            }
            $r_role_priv = $dbAdapter->fetchAll("SELECT roleid, field, value FROM admin_role_priv WHERE roleid!=1 ");
            $r_resource = $dbAdapter->fetchAll("SELECT id, mvcaction FROM resource ");
            $resource = array();
            if (is_array($r_resource) && !empty($r_resource))
            {
                foreach ($r_resource as $i)
                {
                    $j = explode(",", $i['mvcaction']);
                    if (is_array($j) && !empty($j))
                    {
                        foreach ($j as $k)
                        {
                            $mvcaction = explode(":", $k);
                            if (empty($mvcaction[1]))
                            {
                                $mvcaction[1] = '';
                            }
                            $resource[$i['id']][] = array('c'=>$mvcaction[0], 'a'=>$mvcaction[1]);
//                          $resource[$i['id']][]['a'] = 'a'=>$mvcaction[1];
                        }
                    }
//                    $mvcaction = explode(":", $i['mvcaction']);
//                  if (empty($mvcaction[1]))
//                  {
//                      $mvcaction[1] = '';
//                  }
//                  $resource[$i['id']]['c'] = $mvcaction[0];
//                  $resource[$i['id']]['a'] = $mvcaction[1];
                }
            }
            $result = array();
            if (is_array($r_role_priv) && !empty($r_role_priv))
            {
                foreach ($r_role_priv as $i)
                {
                    if ('resource'==$i['field'])
                    {
                        if (is_array($resource[$i['value']]) && !empty($resource[$i['value']]))
                        {
                            foreach ($resource[$i['value']] as $j)
                            {
                                if (empty($result[$i['field']][$j['c']][$i['roleid']]))
                                {
                                    $result[$i['field']][$j['c']][$i['roleid']][] = $j['a'];
                                }
                                else if (!in_array($j['a'], $result[$i['field']][$j['c']][$i['roleid']]))
                                {
                                    $result[$i['field']][$j['c']][$i['roleid']][] = $j['a'];
                                }
                            }
                        }
                    }
//                  if ('resource'==$i['field'] && !empty($resource[$i['value']]['c']))
//                  {
//                      $result[$i['field']][$resource[$i['value']]['c']][$i['roleid']][] = $resource[$i['value']]['a'];
//                  }
                }
                if (is_array($result['resource']) && !empty($result['resource']))
                {
                    foreach ($result['resource'] as $ctr => $i)
                    {
                        if (!isset($exists_mvcctr[$ctr]))
                        {
                            $this->_acl['resource']->add(new Zend_Acl_Resource($ctr));
                            $exists_mvcctr[$ctr] = 1;//add to exists list
                        }
                        if (is_array($i) && !empty($i))
                        {
                            foreach ($i as $roleid => $j)
                            {
    //                            $this->_acl['resource']->addRole(new Zend_Acl_Role($roleid));
                                if (is_array($j) && !empty($j))
                                {
                                    foreach ($j as $k)
                                    {
                                        if (!isset($exists_mvcaction[$roleid][$ctr][$k]))
                                        {
                                            $this->_acl['resource']->allow($roleid, array($ctr), $k);
                                            $exists_mvcaction[$roleid][$ctr][$k] = 1;//add to exists list
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $this->_acl['resource']->addRole(new Zend_Acl_Role(1));
                $this->_acl['resource']->allow(1);
            }
            $coreCache->save($this->_acl['resource'], 'resource');
        }
        return ;
    }

    protected function checkAllow($resource, $action, $throw_exception=false)
    {
        if ('index'==$resource)
        {
            return true;
        }
        $roles = explode(',', $this->_userinfo['roles']);
        if (is_array($roles) && !empty($roles))
        {
            if (in_array(1,$roles))
            {
                return true;
            }
            foreach ($roles as $roleid)
            {
                if ($this->_acl['resource']->isAllowed($roleid, $resource, $action))
                {
                    return true;
                }
            }
        }
        if ($throw_exception)
        {
            throw new Exception('权限不足！');
        }
        else
        {
            return false;
        }
    }

    protected function checkWorkflowProcess($process, $throw_exception=false)
    {
        /*$roles = explode(',', $this->_userinfo['roles']);
        if (is_array($roles) && !empty($roles))
        {
            if (in_array(1,$roles))
            {
                return true;
            }
            foreach ($roles as $roleid)
            {
                if ($this->_acl['process']->isAllowed($roleid, $process, 'check'))
                {
                    return true;
                }
            }
        }
        if ($throw_exception)
        {
            throw new Exception('权限不足！');
        }
        else
        {
            return false;
        }*/
    	return true;
    }

    protected function getProcessList()
    {
        $roles = explode(',', $this->_userinfo['roles']);
        $result = array();
        if (is_array($roles) && !empty($roles))
        {
            foreach ($roles as $roleid)
            {
                $role_process = $this->_processlist[$roleid];
                if (is_array($role_process) && !empty($role_process))
                {
                    foreach ($role_process as $processid)
                    {
                        $result[$processid] = 1;
                    }
                }
            }
            $result = array_keys($result);
        }
        return $result;
    }
    function getConfig()//获取配置信息
    {
    	$db = Zend_Db_Table::getDefaultAdapter();
    	$configrows = $db->fetchAll("select configname, configvalue from config");//获取配置信息
        $configs = array();
    	if (!empty($configrows)){
	       foreach ($configrows as $item){
	          $configs[$item['configname']] = $item['configvalue'];}
    	}//配置信息获取完成
    	return $configs;
    }
}
